const axios = require('axios')
const moment = require('moment')
const githubCon = require('../../config').github
const { GithubUser } = require('../../models')
module.exports = [
  {
    /**
    * @api {get} /github/login [github登录]
    * @apiGroup Github
    * @apiPermission none
    * @apiDescription github登录专用
    * @apiParam {String} code
    * @apiParam {String} state
    */
    url: '/github/login',
    method: 'get',
    request: async (req, res) => {
      const { code, state } = req.query
      if (!code || !state) return res.json({ msg: '参数错误' })
      try {
        const body = await axios.post(githubCon.access_token_url, {
          client_id: githubCon.client_id,
          client_secret: githubCon.client_secret,
          redirect_uri: githubCon.redirect_uri,
          code,
          state
        })
        console.log(body.data)
        const resbody = await axios.get(githubCon.user_info_url + body.data, {
          headers: { 'User-Agent': 'blog' }
        })
        let params = resbody.data
        Object.keys(params).forEach(key => {
          if (!params[key]) delete params[key]
        })
        params.last_visit_time = moment().format('YYYY-MM-DD HH:mm:ss')
        await GithubUser.insertOrUpdate(params)
        res.redirect('/empty?github=' + params.id)
      } catch (error) {
        console.error(error)
        res.status(400).json({error})
      }
    }
  }
]
